﻿' ----------------------------------------------------------------------------------
' Microsoft Developer & Platform Evangelism
' 
' Copyright (c) Microsoft Corporation. All rights reserved.
' 
' THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, 
' EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES 
' OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
' ----------------------------------------------------------------------------------
' The example companies, organizations, products, domain names,
' e-mail addresses, logos, people, places, and events depicted
' herein are fictitious.  No association with any real company,
' organization, product, domain name, email address, logo, person,
' places, or events is intended or should be inferred.
' ----------------------------------------------------------------------------------

Imports System.Globalization
Imports System.IO
Imports System.Net.Browser
Imports Microsoft.Samples.WindowsPhoneCloud.StorageClient.Credentials

Public Class CloudBlobContainer
    Implements ICloudBlobContainer

    Public Sub New(ByVal credentials As StorageClient.Credentials.IStorageCredentials)
        Me.StorageCredentials = credentials
    End Sub

    Public Property StorageCredentials() As IStorageCredentials

    Public Sub CreateContainer(ByVal uri As Uri, ByVal callback As Action(Of CloudOperationResponse(Of Boolean))) Implements ICloudBlobContainer.CreateContainer
        Dim request = CType(WebRequestCreator.ClientHttp.Create(New Uri(String.Format(CultureInfo.InvariantCulture, "{0}?restype=container&timeout=10000", uri))), HttpWebRequest)

        request.Method = "PUT"
        request.Headers("x-ms-version") = "2009-09-19"
        request.Headers("x-ms-blob-type") = "BlockBlob"

        request.BeginGetRequestStream(Sub(ar)
                                          Me.StorageCredentials.SignRequest(request, 0)
                                          request.BeginGetResponse(Sub(asyncResult)
                                                                       Dim req = CType(asyncResult.AsyncState, HttpWebRequest)
                                                                       If req.HaveResponse Then
                                                                           Try
                                                                               Dim res = CType(req.EndGetResponse(asyncResult), HttpWebResponse)
                                                                               If res.StatusCode = HttpStatusCode.Created Then
                                                                                   callback(New CloudOperationResponse(Of Boolean)(True, Nothing))
                                                                               Else
                                                                                   callback(New CloudOperationResponse(Of Boolean)(False, New Exception(String.Format(CultureInfo.InvariantCulture, "Error creating container: {0}", res.StatusDescription))))
                                                                               End If
                                                                           Catch exception As Exception
                                                                               Dim webException = TryCast(exception, WebException)
                                                                               If webException IsNot Nothing Then
                                                                                   Dim resStream = webException.Response.GetResponseStream()
                                                                                   Dim sr = New StreamReader(resStream)
                                                                                   If sr.ReadToEnd().Contains("ContainerAlreadyExists") Then
                                                                                       callback(New CloudOperationResponse(Of Boolean)(False, Nothing))
                                                                                   Else
                                                                                       resStream.Position = 0
                                                                                       callback(New CloudOperationResponse(Of Boolean)(False, webException))
                                                                                   End If
                                                                               Else
                                                                                   callback(New CloudOperationResponse(Of Boolean)(False, exception))
                                                                               End If
                                                                           End Try
                                                                       End If
                                                                   End Sub, request)
                                      End Sub, request)
    End Sub

    Public Sub CreateContainerIfNotExist(ByVal uri As Uri, ByVal callback As Action(Of CloudOperationResponse(Of Boolean))) Implements ICloudBlobContainer.CreateContainerIfNotExist
        Me.DoesContainerExist(uri, Sub(cloudOperationResponse)
                                       If cloudOperationResponse.Exception IsNot Nothing Then
                                           callback(New CloudOperationResponse(Of Boolean)(False, cloudOperationResponse.Exception))
                                       Else
                                           If Not cloudOperationResponse.Response Then
                                               CreateContainer(uri, callback)
                                           Else
                                               callback(New CloudOperationResponse(Of Boolean)(True, Nothing))
                                           End If
                                       End If
                                   End Sub)
    End Sub

    Public Sub DoesContainerExist(ByVal uri As Uri, ByVal callback As Action(Of CloudOperationResponse(Of Boolean))) Implements ICloudBlobContainer.DoesContainerExist
        Dim request = CType(WebRequestCreator.ClientHttp.Create(New Uri(String.Format(CultureInfo.InvariantCulture, "{0}?restype=container&timeout=10000", uri))), HttpWebRequest)

        request.Method = "GET"
        request.BeginGetResponse(Sub(asyncResult)
                                     Dim req = CType(asyncResult.AsyncState, HttpWebRequest)
                                     If req.HaveResponse Then
                                         Try
                                             Dim res = CType(req.EndGetResponse(asyncResult), HttpWebResponse)
                                             callback(New CloudOperationResponse(Of Boolean)(True, Nothing))
                                         Catch exception As Exception
                                             Dim webException = TryCast(exception, WebException)
                                             If webException IsNot Nothing Then
                                                 Dim resStream = webException.Response.GetResponseStream()
                                                 Dim sr = New StreamReader(resStream)
                                                 Dim responseContent = sr.ReadToEnd()
                                                 If responseContent.Contains("ResourceNotFound") Then
                                                     callback(New CloudOperationResponse(Of Boolean)(False, Nothing))
                                                 Else
                                                     callback(New CloudOperationResponse(Of Boolean)(False, exception))
                                                 End If
                                             Else
                                                 callback(New CloudOperationResponse(Of Boolean)(False, exception))
                                             End If
                                         End Try
                                     End If
                                 End Sub, request)
    End Sub
End Class